<template>
  <div>
    <div class="nav">
      <!-- 路由 params 参数 字符串格式 -->
      <!-- <router-link
        active-class="active"
        v-for="message in messageList"
        :key="message.id"
        :to="`/home/messages/detail/${message.id}/${message.msg}`"
      >
        {{ message.msg }}
      </router-link> -->
      <!-- 路由 params 参数 对象格式 -->
      <router-link
        v-for="message in messageList"
        :key="message.id"
        :to="{
          name: 'Detail', // 使用命名路由,与router中配置的路由name对应
          // params 参数对象格式只能与name搭配使用，不能与path搭配使用
          params: {
            id: message.id,
            msg: message.msg,
          },
        }"
      >
        {{ message.msg }}
        <button @click="pushShow(message)">push跳转</button>
        <button @click="replaceShow(message)">replace跳转</button>
      </router-link>
    </div>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "Messages",
  data() {
    return {
      messageList: [
        {
          id: "1",
          msg: "msg1",
        },
        {
          id: "2",
          msg: "msg2",
        },
        {
          id: "3",
          msg: "msg3",
        },
        {
          id: "4",
          msg: "msg5",
        },
        {
          id: "5",
          msg: "msg5",
        },
      ],
    };
  },
  methods: {
    pushShow({ id, msg }) {
      this.$router
        .push({
          name: "Detail",
          params: {
            id,
            msg,
          },
        })
        .catch((err) => {
          // 避免路由重复点击报错
          console.log("pushShow", err);
        });
    },
    replaceShow({ id, msg }) {
      this.$router
        .replace({
          name: "Detail",
          params: {
            id,
            msg,
          },
        })
        .catch((err) => {
          // 避免路由重复点击报错
          console.log("replaceShow", err);
        });
    },
  },
  beforeDestroy() {
    console.log("messages组件即将销毁");
  },
  // 只有被缓存的路由组件才有activated和deactivated
  activated() {
    console.log("messases组件被激活");
    this.change();
  },
  deactivated() {
    console.log("messases组件被激活组件失活了");
  },
};
</script>

<style scoped>
.nav {
  display: flex;
  align-items: center;
  justify-content: center;
  list-style: none;
  padding: 0;
  margin: 0;
  gap: 20px;
}
</style>
